package com.nkym.wypan.websocket;

import cn.hutool.json.JSONUtil;
import com.nkym.wypan.enums.socket.MessageTypeEnum;
import com.nkym.wypan.model.entity.chat.Message;
import com.nkym.wypan.service.WebSocketService;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.annotation.Resource;
import java.io.IOException;

public class CustomSocketHandler extends TextWebSocketHandler {

    @Resource
    WebSocketService webSocketService;

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
        String payload = message.getPayload();
        Message msg = JSONUtil.toBean(payload, Message.class);
        Integer type = msg.getType();
        MessageTypeEnum messageTypeEnum = MessageTypeEnum.of(type);

        switch (messageTypeEnum) {
            case AUTH_ROOM:
                webSocketService.userJoinRoom(session, msg);
                break;
            case CHAT:
                webSocketService.sendChatMsg(session, msg);
        }

    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        webSocketService.addSession(session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {

        webSocketService.removeSession(session);
    }


}